#include "engine.h"

//global variable
GEngine		g_engine;

// static varaiable initialize
GEngine* GEngine::m_pEngine = 0;
GGame* GEngine::m_pGame = 0;
GRenderer* GEngine::m_pRenderer = 0;

GEngine::GEngine()
{
    m_pEngine = this;

    m_pRenderer = NULL;
    m_pGame = NULL;
    m_pLoop = NULL;
}

GEngine::~GEngine()
{
    if(m_pEngine)
        EngineEnd();
}

GEngine* GEngine::GetEngine()
{
    return m_pEngine;
}

GRenderer* GEngine::GetRenderer()
{
    return m_pRenderer;
}

GGame* GEngine::GetGame()
{
    return m_pGame;
}

bool GEngine::EngineInitialize(GGame* pGame)
{
    if(!pGame)
        return false;

    m_pGame = pGame;
    if(!m_pGame->GameInitialize())
        return false;

    m_pLoop = new GLoop();
    if(!m_pLoop)
        return false;

    m_pRenderer = new GRenderer();
    if(!m_pRenderer || !m_pRenderer->RendererInitialize(m_pGame->GetWindow()))
        return false;

    bool b = true;
    if(b && !m_pRenderer->RendererInitialize(m_pGame->GetWindow()))
        return false;

    return true;
}

void GEngine::EngineStart()
{
    Q_ASSERT(m_pLoop && m_pRenderer && m_pGame);

    m_pGame->GameStart();
    m_pLoop->StartLoop();
    m_pRenderer->RendererStart();
}

void GEngine::EngineEnd()
{
    qDebug() << "GEngine::End";

//    GuiLayers_itor layer_itor;
//    for(layer_itor = m_layer_list.begin(); layer_itor != m_layer_list.end(); layer_itor++)
//    {
//        GuiLayer* pLayer = *layer_itor;
//        if(pLayer)
//        {
//            //pLayer->Shutdown();

//            qDebug() << "delete pLayer";
//            delete pLayer;
//        }
//    }


//    GameObjects_itor go_itor;
//    for(go_itor = m_go_list.begin(); go_itor != m_go_list.end(); go_itor++)
//    {
//        GameObject* pGo = *go_itor;
//        if(pGo)
//        {
//            //pGo->Shutdown();

//            qDebug() << "delete pGo";
//            delete pGo;
//        }
//    }

    if(m_pGame)
    {
        m_pGame->GameEnd();
        //delete m_pGame;
    }

    if(m_pLoop)
    {
        m_pLoop->StopLoop();
        delete m_pLoop;
    }

    if(m_pRenderer)
    {
        m_pRenderer->RendererEnd();
        delete m_pRenderer;
    }

    qDebug() << "delete GEngine";
    m_pEngine = NULL;
    //delete this;
}

void GEngine::Tick(double elapsed)
{
	if(elapsed == 0)
		return;

    Q_ASSERT(m_pRenderer && m_pGame);

    m_pRenderer->Render(elapsed);
    m_pGame->Update(elapsed);
}

